package com.dawan.sbjy.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dawan.sbjy.Config.Result;
import com.dawan.sbjy.Config.myExcep;
import com.dawan.sbjy.Rabbit.RabbitProducer;
import com.dawan.sbjy.dao.LoginDao;
import com.dawan.sbjy.dao.UserDao;
import com.dawan.sbjy.service.ifac.RegisteService;
import com.dawan.sbjy.service.impl.UserService;
import com.dawan.sbjy.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import org.apache.log4j.Logger;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.Email;
import javax.xml.ws.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@Validated
public class LoginController {
    public static final Logger logger = Logger.getLogger(LoginController.class);
    @Value("${sbjy.appId}")
    private String appID;
    @Value("${sbjy.appSecrct}")
    private String appSecrct;
    @Autowired
    public HttpClientUtils httpClientUtils;
    @Autowired
    public GetToken getToken;
    @Autowired
    public UserDao userDao;
    @Autowired
    UserService userService;
    @Autowired
    RegisteService registeService;

    @RequestMapping(value = "/login/commWxLogin",method = RequestMethod.POST)
    public Result login(@RequestBody JSONObject param) {
         Map<String,String> map=new HashMap<String ,String>();
         map.put("grant_type","authorization_code");
         map.put("js_code",(String) param.get("code"));
         map.put("appid",this.appID);
         map.put("secret",this.appSecrct);
        String url="https://api.weixin.qq.com/sns/jscode2session";
        JSONObject jsonObject = JSON.parseObject( httpClientUtils.post( url,map ));
        jsonObject.get("openid");
        if(jsonObject.get("openid")== null){
            throw new myExcep(412,"登录失败 openid错误");
        }
        String  session_key=jsonObject.getString("session_key");
        //需要签名的数据
        String sha1=param.getJSONObject("userInfo").getString("rawData")+jsonObject.getString("session_key");
        //签名后数据
        String sha11= Sha.getSha1(sha1);
        if(sha11.equals(param.getJSONObject("userInfo").getString("signature"))==false){
            throw new myExcep(500,"签名验证错误");
        }
        //对微信（个人信息数据）加密数据进行解密
        String weixinUserInfo= WXCore.decrypt(this.appID,param.getJSONObject("userInfo").getString("encryptedData") , jsonObject.getString("session_key"),param.getJSONObject("userInfo").getString("iv"));

        String sessionKey = null;
        JSONObject wxUserinf = JSON.parseObject(weixinUserInfo);
        String openId=wxUserinf.getString("openId");

        //获取数据库用户信息
        List<HashMap> dbUserInfo = userDao.findUserByOpenId(openId);
        JSONObject retUserObj=wxUserinf;
        Map<String,Object> resultMap=new HashMap<>();
        if(dbUserInfo.size()==0){
            String uuid = UUID.randomUUID().toString();
            String strmd58= Md5Util.getMD5(uuid).substring(0,8);
            retUserObj.put("userid",uuid);
            retUserObj.put("channelcode",strmd58);
            System.out.println(retUserObj);
            // 写入用户信息到DB中
            int insert=userDao.insertUser(retUserObj);
            System.out.println(insert);
            sessionKey=getToken.createToken(retUserObj.toString());
            resultMap.put("accessToken",sessionKey);
            resultMap.put("userInfo",retUserObj);
//            return ResultUtil.success(resultMap,"获取成功");
        }else if(Integer.parseInt(dbUserInfo.get(0).get("ur_status").toString())==2){
//            return ResultUtil.success();
        }else{
            retUserObj.put("channelcode",dbUserInfo.get(0).get("channelcode"));
            retUserObj.put("phone",dbUserInfo.get(0).get("phone"));
            retUserObj.put("userid",dbUserInfo.get(0).get("user_id"));
            retUserObj.put("user_type",dbUserInfo.get(0).get("channelcode"));
            retUserObj.put("sysname",dbUserInfo.get(0).get("sysname"));
            retUserObj.put("country",dbUserInfo.get(0).get("country"));
            sessionKey=getToken.createToken(retUserObj.toString());
            resultMap.put("accessToken",sessionKey);
            resultMap.put("userInfo",retUserObj);
//            return ResultUtil.success(resultMap,"获取成功");
        }
        //更新用户的sessionkey
        String userid=retUserObj.getString("userid");
        userDao.updateSessionkey(userid,session_key);
        return ResultUtil.success(resultMap,"获取成功");
    }
    @RequestMapping(value = "/anno/test",method = RequestMethod.GET)
    public  Result decryPhone(HttpSession session){
        String phonedata=session.getId();
        //
        return  ResultUtil.success(phonedata,"获取成功8080");
    }

    @RequestMapping(value = "/wx/decryPhone",method = RequestMethod.POST)
    public  Result decryPhone(@RequestBody JSONObject param){
        JSONObject phonedata=userService.setPhone(param);
        //
        return  ResultUtil.success(phonedata,"获取成功");
    }
//    @RequestMapping(value = "/wx/addressupload",method = RequestMethod.GET)
//    public  Result addressupload(String data ){
//        return  ResultUtil.success(data,"获取成功");
//    }
    //用户登录
    @RequestMapping(value = "/user/login",method = RequestMethod.GET)
        public  Result userlogin(@RequestParam(required = true) String email,@RequestParam(required = true) String password, HttpSession session,HttpServletRequest request) {
        //根据用户名和密码去查询用户是否存在，如果存在将个人信息存入session
        Map userinf = userService.findUserByPassword(email, password);
        if (userinf.get("user_id") != null) {
            session.setAttribute("user_id", userinf.get("user_id"));
            HashMap<String,String> usertoken=new HashMap<>();
            usertoken.put("user_id",userinf.get("user_id").toString());
            return ResultUtil.success(usertoken, "登陆成功");
        } else {
            return ResultUtil.error("userid异常","登陆失败");
        }

    }
    //用户注册
    @RequestMapping(value = "/user/registe",method = RequestMethod.GET)
    public  Result userregiste(@RequestParam(required = true) String password,@RequestParam(required = true) @Email(message = "should be email format")  String email,@RequestParam(required = true) String code) {

        //验证邮箱和code一致性，并进行用户注册
        int userinf = userService.usergeiste(code, password,email);
        if (userinf>0) {
            return ResultUtil.success("1", "注册成功");
        } else {
            return ResultUtil.error("2","注册失败");
        }

    }

    //队列测试
    @RequestMapping(value = "/admin/queuetest",method = RequestMethod.GET)
    public  Result ququetest() {
        userService.userqueue("1");
        return ResultUtil.error("2","测试成功");

    }
    //邮箱注册发送验证码
    @RequestMapping(value = "/admin/registemailcode",method = RequestMethod.POST)
    public  Result mailcode(@RequestBody JSONObject emailparams) {
        Result result=registeService.emailcode(emailparams.getString("email"));
        return ResultUtil.success("2","邮箱发送成功");

    }
}

